<template>
    <tableLayout :columns="columns" :get="getData" :params="params"
        :row-selection="{ selectedRowKeys: selectedRowKeys, onChange: onSelectChange }" ref="layout">
        <template #button>
            <MenuToolBar :selectedRowKeys="selectedRowKeys">
                <template #button>
                    <a-button type="primary" btnMark="Btn_hzym6lr" style="margin-left: 20px" @click="del" danger>删除
                    </a-button>
                </template>
            </MenuToolBar>
        </template>

        <template #operationMore="item">
            <LinkBtnPanel :record="item.value.record"></LinkBtnPanel>
        </template>
    </tableLayout>

    <a-modal :title="formState.Id ? '编辑数据源' : '新增数据源'" v-model:visible="model_visible" :confirm-loading="confirmLoading"
        @ok="model_handleOk" width="900px">
        <a-form ref="formRef" :model="formState" :label-col="labelCol" :wrapper-col="wrapperCol" :rules="rules"
            layout="inline" class="comform">
            <a-form-item label="名称" style="width: calc(50% - 20px);" class="form__item" name="CName">
                <a-input v-model:value="formState.CName" />
            </a-form-item>
            <a-form-item label="英文名称" style="width: calc(50% - 20px);" class="form__item" name="EName">
                <a-input v-model:value="formState.EName" />
            </a-form-item>

            <a-form-item label="数据库类型" style="width: calc(50% - 20px);" class="form__item" name="DBType">
                <a-select v-model:value="formState.DBType" style="width: 100%;">
                    <a-select-option v-for="item in DBTypeOptions" :key="item.Val" :value="item.Val">
                        {{ item.Name }}
                    </a-select-option>
                </a-select>
            </a-form-item>

            <a-form-item label="状态" style="width: calc(50% - 20px);" class="form__item" name="IsValid">
                <a-radio-group name="radioGroup" v-model:value="formState.IsValid">
                    <a-radio :value="true">启用</a-radio>
                    <a-radio :value="false">停用</a-radio>
                </a-radio-group>
            </a-form-item>
            <a-form-item label="连接字符串" style="width: calc(100% - 20px);" class="form__item" name="ConnectionString"
                :labelCol="{ span: 3 }" :wrapperCol="{ span: 21 }">
                <a-textarea v-model:value="formState.ConnectionString" placeholder="连接字符串" :rows="4" />
            </a-form-item>
            <a-form-item label="备注" style="width: calc(100% - 20px);" class="form__item" name="Description"
                :labelCol="{ span: 3 }" :wrapperCol="{ span: 21 }">
                <a-textarea v-model:value="formState.Description" placeholder="备注" :rows="4" />
            </a-form-item>
            <!--增加一个测试连接按钮-->
            <a-form-item label="测试连接" style="width: calc(100% - 20px);" class="form__item" name="TestConnection"
                :labelCol="{ span: 3 }" :wrapperCol="{ span: 21 }">
                <a-button type="primary" @click="testConnection">测试连接</a-button>
            </a-form-item>
        </a-form>
    </a-modal>
</template>


<script lang="ts" setup>
import { getData, deleteDynamicDataSource, setDynamicDataSource, dBTestConnection } from '@/api/dynamic-datasource/dynamic-datasource';
import { provide, ref, h, VNode, UnwrapRef, reactive } from 'vue';
import tableLayout from '@/components/tableLayout/tableLayout.vue';
import { Descriptions, Layout, message } from 'ant-design-vue';
import { DynamicDataSourceInput } from '@/types/api/dynamic-datasource/dynamic-datasource';
import MenuToolBar from '@/components/toolbar/menuToolBar.vue';
import LinkBtnPanel from '@/components/linkbtn/linkBtnPanel.vue';

const layout = ref();

//表单对象
const formState: UnwrapRef<DynamicDataSourceInput> = reactive({
    Id: '',
    CName: '',
    Description: '',
    EName: '',
    DbType: 0,
    ConnectionString: '',
    IsValid: false,
});

const DBTypeOptions = ref([
    { 'Name': 'MySql', 'Val': 0 },
    { 'Name': 'SqlServer', 'Val': 1 },
    { 'Name': 'Sqlite', 'Val': 2 },
    { 'Name': 'Oracle', 'Val': 3 },
    { 'Name': 'PostgreSQL', 'Val': 4 }
]);

const codeTreeOptions = ref<any>([]);

//列表
const columns = [
    { title: '名称', dataIndex: 'CName' },
    { title: '英文名称', dataIndex: 'EName' },
    {
        title: '数据库类型', dataIndex: 'DbType', customRender: function ({ text }): VNode {
            let DbTypeTxt = '未知';
            DBTypeOptions.value.forEach(item => {
                if (item.Val == text) {
                    DbTypeTxt = item.Name;
                }
            })
            return h('div', {
                style: {
                    color: 'red'
                }
            }, DbTypeTxt);
        }
    },
    {
        title: '状态', dataIndex: 'IsValid', customRender: function ({ text }): VNode {

            return h('div', {
                style: {
                    color: 'red'
                }
            }, text ? '启用' : '停用');
        }
    }
]

// 规则
const rules = {
    CName: [{ required: true, message: '请输入名称', trigger: 'change' }],
    EName: [{ required: true, message: '请输入英文名称', trigger: 'change' }],
    ConnectionString: [{ required: true, message: '请输入入口方法', trigger: 'change' }]
}

let params = ref();

const add = () => {
    model_visible.value = true;
    Object.assign(formState, {
        Id: '',
        EName: '',
        CName: '',
        DbType: 0,
        ConnectionString: '',
        IsValid: false,
        Description: '',
    });
}

const edit = (event: any, item: any) => {
    let selectItem = item;
    if (!item) {
        if (!selectedRowKeys.value || selectedRowKeys.value.length <= 0 || selectedRowKeys.value.length > 1) {
            message.warning('请先选择一条数据!');
            return;
        }
        selectItem = selectedRows.value[0];
    }
    model_visible.value = true;
    Object.assign(formState, selectItem);
}

const del = (event: any, item: any) => {
    let selectId = item.Id;
    if (!selectId) {
        if (!selectedRowKeys.value || selectedRowKeys.value.length <= 0 || selectedRowKeys.value.length > 1) {
            message.warning('请先选择一条数据!');
            return;
        }
        selectId = selectedRows.value[0].Id;
    }

    deleteDynamicDataSource({ Id: selectId }).then(() => {
        message.success("删除成功!");
        layout.value.getData();
    }).catch(err => {
        message.error(err.message || "删除失败!")
        confirmLoading.value = false;
    })
}

const model_visible = ref<boolean>(false);
const confirmLoading = ref<boolean>(false);
const formRef = ref()

const model_handleOk = () => {
    formRef.value.validate().then(() => {
        confirmLoading.value = true;
        setDynamicDataSource(formState).then(e => {
            message.success("添加成功！");
            confirmLoading.value = false;
            model_visible.value = false;
            layout.value.getData();
        }).catch(err => {
            message.error(err.message || "添加失败!")
            confirmLoading.value = false;
        })
    }).catch(() => {
        message.error('请检查必填项是否全部填写!');
    })
}

const testConnection = () => {
    formRef.value.validate().then(() => {
        confirmLoading.value = true;
        dBTestConnection(formState).then(e => {
            if (e.data.ErrorCode == "000000") {
                message.success("连接成功！");
            } else {
                message.error(e.data.ErrorMessage);
            }
            confirmLoading.value = false;
        }).catch(err => {
            message.error(err.message || "连接失败!")
            confirmLoading.value = false;
        })
    }).catch(() => {
        message.error('请检查必填项是否全部填写!');
    })
}

// 多选
const selectedRowKeys = ref<any[]>([]);
const selectedRows = ref<any[]>([]);
const onSelectChange = (keys: [], rows: any) => {
    selectedRowKeys.value = keys;
    selectedRows.value = rows;
}

const labelCol = { span: 6 };
const wrapperCol = { span: 18 };

provide('parentMethods', { add: add, edit: edit, del: del });
</script>

<style lang="scss" scoped>
.comform {
    & .form__item {
        margin-bottom: 16px;

        & .ant-form-item-label {
            flex-grow: 1 !important;
            flex-shrink: 0;
        }
    }
}
</style>
<style lang="scss">
.comform {
    & .form__item {
        margin-bottom: 16px;

        & .ant-form-item-label {
            flex-grow: 1;
            flex-shrink: 0;
        }
    }
}
</style>